//
//  HomeViewController.swift
//  Keyboard
//
//  Created by xinglian on 2022/12/16.
//

import UIKit
import SwiftyJSON

class HomeViewController: BaseViewController {
    @IBOutlet var app: UILabel!
    @IBOutlet var firmware: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        BLE.startScan()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
        BleDataTool.share.firmwareVersion()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    override func initUI() {
        ///添加长按手势
        let long = UILongPressGestureRecognizer()
        long.addTarget(self, action: #selector(acitonForLong))
        long.minimumPressDuration = 3
        self.view.addGestureRecognizer(long)
        
        let dict = Bundle.main.infoDictionary!
        let version = dict["CFBundleShortVersionString"] as! String
        let build = dict["CFBundleVersion"] as! String
        app.text = LS("APP 版本:") + "V" + version + ".\(build)"
        
    }
    ///长安手势恢复出厂设置
    @objc func acitonForLong(_ sender:UILongPressGestureRecognizer){
        if sender.state == .ended{
            self.alert(LS("注意"),LS("将键盘恢复出厂设置？"),nil, {
                BleDataTool.share.reset()
            })
        }
    }
    
    @IBAction func actionForBtn(_ sender: UIButton) {
        print("点击  按钮 \(sender.tag)")
        switch sender.tag{
        case 201:
            let vc = ChooseViewController()
            self.push(vc, true)
        case 202:
            let vc = ConnectViewController()
            self.push(vc, true)
        case 203:
            let vc = NoteViewController()
            self.push(vc,true)
        default:
            break
        }
    }
    
    
    func checkOTA(_ p:String,_ v:String){
        NetworkTool.request(.checkUpdate(p, v)) { response in
            let data = response["data"].dictionaryValue
            guard let firmware = data["firmware"]?.dictionaryValue else{return}
            guard let versionCode = firmware["versionCode"]?.intValue else{return}
            if versionCode > Int(v) ?? 0{
                self.alert(LS("注意"),LS("固件有更新，前去更新？"),nil, {
                    OTAViewController.show(firmware)
                })
            }
        }
    }
    
}

extension HomeViewController{
    override func addNotify() {
        NotificationCenter.default.addObserver(self, selector: #selector(actionForBLE322Response), name: BLE322Response, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(checkFirmwareNote), name: BLE3221Response, object: nil)
        
    }
 
    @objc func actionForBLE322Response(notify:Notification){
        guard let param = notify.object as? [String:String] else{return}
        let version = param["version"] ?? ""
        let product = param["product"] ?? ""
        let version_net = param["version_net"] ?? ""
        firmware.text = LS("屏幕固件 版本:") + "V" + version
        checkOTA(product, version_net)
    }
    
    ///同步手机本地的记事本和键盘的记事本
    @objc func checkFirmwareNote(notify:Notification){
        guard let stampArr = notify.object as? [Int] else{return}
        NoteTool.find { array in
            let local_stamp_arr = array.compactMap{Int($0.stamp)}
            let temp = stampArr.filter{!local_stamp_arr.contains($0 - 946656000)}
            for stamp in temp{
                BleDataTool.share.delete("\(stamp)")
            }
        }
    }
}
